<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 分类管理</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 分类管理页面 -->
            <div id="categories" class="content-page active">
                <div class="page-header">
                    <h2>图书分类管理</h2>
                    <button class="btn btn-primary" onclick="showAddCategoryModal()">
                        <i class="fas fa-plus"></i>
                        添加分类
                    </button>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>分类名称</th>
                                <th>描述</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="categoryTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="categoryPagination"></div>
                <div class="pagination-tools" id="categoryPaginationTools"></div>
            </div>
        </main>
    </div>

    <!-- 模态框 -->
    <div id="modalOverlay" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3 id="modalTitle">标题</h3>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
            </div>
            <div class="modal-footer" id="modalFooter">
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script>
        // API基础配置
        const API_BASE_URL = 'http://118.31.223.190:8080';

        // 通用API请求函数
        class ApiClient {
            constructor() {
                this.baseURL = API_BASE_URL;
            }

            async request(url, options = {}) {
                const isForm = options && options.body instanceof FormData;
                const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
                const config = { headers, ...options };

                try {
                    const response = await fetch(`${this.baseURL}${url}`, config);
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    return data;
                } catch (error) {
                    console.error('API请求失败:', error);
                    throw error;
                }
            }

            async get(url, params = {}) {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = queryString ? `${url}?${queryString}` : url;
                return this.request(fullUrl, { method: 'GET' });
            }

            async post(url, data = {}) {
                if (data instanceof FormData) {
                    return this.request(url, { method: 'POST', body: data });
                }
                return this.request(url, { method: 'POST', body: JSON.stringify(data) });
            }

            async put(url, data = {}) {
                return this.request(url, {
                    method: 'PUT',
                    body: JSON.stringify(data)
                });
            }

            async delete(url) {
                return this.request(url, { method: 'DELETE' });
            }
        }

        // 创建API客户端实例
        const api = new ApiClient();

        // 图书分类管理API
        const BookCategoryAPI = {
            // 创建分类
            createCategory: (categoryData) => api.post('/api/book-categories', categoryData),
            
            // 更新分类
            updateCategory: (categoryData) => api.put('/api/book-categories', categoryData),
            
            // 删除分类
            deleteCategory: (categoryId) => api.delete(`/api/book-categories/${categoryId}`),
            
            // 获取分类详情
            getCategoryById: (categoryId) => api.get(`/api/book-categories/${categoryId}`),
            
            // 获取所有分类
            getAllCategories: () => api.get('/api/book-categories')
        };

        // 工具函数
        const Utils = {
            // 显示加载状态
            showLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.add('active');
                }
            },

            // 隐藏加载状态
            hideLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.remove('active');
                }
            },

            // 显示消息提示
            showMessage: (message, type = 'info', duration = 3000) => {
                const messageContainer = document.getElementById('messageContainer');
                if (!messageContainer) return;

                const messageEl = document.createElement('div');
                messageEl.className = `message ${type}`;
                
                const iconMap = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle'
                };

                messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                messageContainer.appendChild(messageEl);

                // 自动移除消息
                setTimeout(() => {
                    if (messageEl.parentElement) {
                        messageEl.remove();
                    }
                }, duration);
            },

            // 创建分页组件
            createPagination: (currentPage, totalPages, onPageChange) => {
                const pagination = document.createElement('div');
                pagination.className = 'pagination';

                // 上一页按钮
                const prevBtn = document.createElement('button');
                prevBtn.textContent = '上一页';
                prevBtn.disabled = currentPage <= 1;
                prevBtn.onclick = () => onPageChange(currentPage - 1);
                pagination.appendChild(prevBtn);

                // 页码按钮
                const startPage = Math.max(1, currentPage - 2);
                const endPage = Math.min(totalPages, currentPage + 2);

                if (startPage > 1) {
                    const firstBtn = document.createElement('button');
                    firstBtn.textContent = '1';
                    firstBtn.onclick = () => onPageChange(1);
                    pagination.appendChild(firstBtn);

                    if (startPage > 2) {
                        const ellipsis = document.createElement('span');
                        ellipsis.textContent = '...';
                        ellipsis.style.padding = '0.5rem';
                        pagination.appendChild(ellipsis);
                    }
                }

                for (let i = startPage; i <= endPage; i++) {
                    const pageBtn = document.createElement('button');
                    pageBtn.textContent = i;
                    pageBtn.className = i === currentPage ? 'active' : '';
                    pageBtn.onclick = () => onPageChange(i);
                    pagination.appendChild(pageBtn);
                }

                if (endPage < totalPages) {
                    if (endPage < totalPages - 1) {
                        const ellipsis = document.createElement('span');
                        ellipsis.textContent = '...';
                        ellipsis.style.padding = '0.5rem';
                        pagination.appendChild(ellipsis);
                    }

                    const lastBtn = document.createElement('button');
                    lastBtn.textContent = totalPages;
                    lastBtn.onclick = () => onPageChange(totalPages);
                    pagination.appendChild(lastBtn);
                }

                // 下一页按钮
                const nextBtn = document.createElement('button');
                nextBtn.textContent = '下一页';
                nextBtn.disabled = currentPage >= totalPages;
                nextBtn.onclick = () => onPageChange(currentPage + 1);
                pagination.appendChild(nextBtn);

                return pagination;
            }
        };

        // 全局变量
        let currentUser = null;
        let currentPageNum = 1;
        let currentPageSize = 10;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
        });

        // 初始化应用
        function initializeApp() {
            // 使用通用权限检查
            if (!initializePagePermission()) {
                return;
            }
            
            currentUser = authManager.getCurrentUser();
            
            // 生成动态菜单
            generateSidebarMenu();
            
            // 更新用户信息
            document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
            
            // 先渲染一个默认的分页工具栏，数据返回后会再次渲染覆盖
            renderPaginationTools('categoryPaginationTools', 1,
                (n) => { currentPageNum = n; loadCategories(n); },
                (size) => { currentPageSize = size; currentPageNum = 1; loadCategories(1); }
            );
            // 加载分类数据
            loadCategories();
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
            }
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 切换侧边栏
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 退出登录
        function logout() {
            currentUser = null;
            localStorage.removeItem('currentUser');
            window.location.href = 'login.html';
            Utils.showMessage('已退出登录', 'info');
        }

        // 显示通知
        function showNotifications() {
            window.location.href = 'notifications.html';
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 加载分类数据（分页）
        async function loadCategories(page = 1) {
            try {
                Utils.showLoading();
                
                // 若后端暂无分页接口，前端在拿到全部后做分页切片
                const respAll = await BookCategoryAPI.getAllCategories();
                
                if (respAll.result === 'SUCCESS') {
                    const all = respAll.data || [];
                    const total = all.length;
                    const pages = Math.max(1, Math.ceil(total / currentPageSize));
                    const start = (page - 1) * currentPageSize;
                    const pageData = all.slice(start, start + currentPageSize);
                    renderCategoryTable(pageData);
                    renderPagination('categoryPagination', page, pages, loadCategories);
                    renderPaginationTools('categoryPaginationTools', pages,
                        (n) => { currentPageNum = n; loadCategories(n); },
                        (size) => { currentPageSize = size; currentPageNum = 1; loadCategories(1); }
                    );
                } else {
                    Utils.showMessage(respAll.message || '加载分类数据失败', 'error');
                    // 兜底：至少渲染工具栏（1页）
                    renderPaginationTools('categoryPaginationTools', 1,
                        (n) => { currentPageNum = n; loadCategories(n); },
                        (size) => { currentPageSize = size; currentPageNum = 1; loadCategories(1); }
                    );
                }
            } catch (error) {
                Utils.showMessage('加载分类数据失败', 'error');
                console.error('Categories load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }

        // 渲染分类表格
        function renderCategoryTable(categories) {
            const tbody = document.getElementById('categoryTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = categories.map(category => `
                <tr>
                    <td>${category.categoryId}</td>
                    <td>${category.categoryName}</td>
                    <td>${category.description || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editCategory(${category.categoryId})">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteCategory(${category.categoryId})">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 显示添加分类模态框
        function showAddCategoryModal() {
            showModal('添加分类', `
                <form id="addCategoryForm">
                    <div class="form-group">
                        <label for="addCategoryName">分类名称</label>
                        <input type="text" id="addCategoryName" name="categoryName" required>
                    </div>
                    <div class="form-group">
                        <label for="addDescription">描述</label>
                        <textarea id="addDescription" name="description" rows="3"></textarea>
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitAddCategory()">添加</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
        }

        // 提交添加分类
        async function submitAddCategory() {
            const form = document.getElementById('addCategoryForm');
            const formData = new FormData(form);
            
            const categoryData = {
                categoryName: formData.get('categoryName'),
                description: formData.get('description')
            };
            
            try {
                Utils.showLoading();
                const response = await BookCategoryAPI.createCategory(categoryData);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('分类添加成功', 'success');
                    closeModal();
                    loadCategories();
                } else {
                    Utils.showMessage(response.message || '添加分类失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '添加分类失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 编辑分类
        async function editCategory(categoryId) {
            try {
                Utils.showLoading();
                const response = await BookCategoryAPI.getCategoryById(categoryId);
                
                if (response.result === 'SUCCESS') {
                    const category = response.data;
                    showModal('编辑分类', `
                        <form id="editCategoryForm">
                            <input type="hidden" id="editCategoryId" value="${category.categoryId}">
                            <div class="form-group">
                                <label for="editCategoryName">分类名称</label>
                                <input type="text" id="editCategoryName" name="categoryName" value="${category.categoryName}" required>
                            </div>
                            <div class="form-group">
                                <label for="editDescription">描述</label>
                                <textarea id="editDescription" name="description" rows="3">${category.description || ''}</textarea>
                            </div>
                        </form>
                    `, `
                        <button class="btn btn-primary" onclick="submitEditCategory()">保存</button>
                        <button class="btn btn-secondary" onclick="closeModal()">取消</button>
                    `);
                } else {
                    Utils.showMessage(response.message || '获取分类信息失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '获取分类信息失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 提交编辑分类
        async function submitEditCategory() {
            const form = document.getElementById('editCategoryForm');
            const formData = new FormData(form);
            
            const categoryData = {
                categoryId: parseInt(formData.get('categoryId')),
                categoryName: formData.get('categoryName'),
                description: formData.get('description')
            };
            
            try {
                Utils.showLoading();
                const response = await BookCategoryAPI.updateCategory(categoryData);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('分类更新成功', 'success');
                    closeModal();
                    loadCategories();
                } else {
                    Utils.showMessage(response.message || '更新分类失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '更新分类失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 删除分类
        async function deleteCategory(categoryId) {
            if (!confirm('确定要删除该分类吗？此操作不可恢复！')) return;
            
            try {
                Utils.showLoading();
                const response = await BookCategoryAPI.deleteCategory(categoryId);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('分类删除成功', 'success');
                    loadCategories();
                } else {
                    Utils.showMessage(response.message || '删除分类失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '删除分类失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 显示模态框
        function showModal(title, body, footer) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalBody').innerHTML = body;
            document.getElementById('modalFooter').innerHTML = footer;
            document.getElementById('modalOverlay').classList.add('active');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('modalOverlay').classList.remove('active');
        }

        // 渲染分页组件
        function renderPagination(containerId, currentPage, totalPages, onPageChange) {
            const container = document.getElementById(containerId);
            if (!container) return;
            
            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }
            
            container.innerHTML = '';
            container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
        }

        // 渲染分页工具栏：跳页与每页条数
        function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
            const c = document.getElementById(containerId);
            if (!c) return;
            c.innerHTML = `
                <span>到第</span>
                <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
                <span>页</span>
                <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
                <span style="margin-left:12px">每页</span>
                <select id="${containerId}-size" style="width:90px">
                    <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
                    <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
                    <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
                    <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
                </select>
            `;
            const goBtn = document.getElementById(`${containerId}-go`);
            const jumpInput = document.getElementById(`${containerId}-jump`);
            const sizeSelect = document.getElementById(`${containerId}-size`);
            if (goBtn && jumpInput) {
                goBtn.onclick = () => {
                    const n = parseInt(jumpInput.value || '1', 10);
                    const page = Math.min(Math.max(1, n), totalPages);
                    onJump(page);
                };
            }
            if (sizeSelect) {
                sizeSelect.onchange = () => {
                    const size = parseInt(sizeSelect.value, 10);
                    onSizeChange(size);
                };
            }
        }
    </script>
</body>
</html>
